package com.fast.cron.db.service;

import com.fast.cron.db.RowMapper;
import com.fast.cron.db.dao.AbstractDao;
import com.fast.cron.db.dao.ScheduleJobDao;
import com.fast.cron.db.entry.ScheduleJob;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Leo Jie
 * @date: 2018-10-04 20:23
 * @version: v1.0
 */
public class ScheduleJobService extends AbstractDao implements ScheduleJobDao {
    @Override
    public long addJobToSchedule(ScheduleJob scheduleJob) throws SQLException {
        String sql = "insert into fast_cron_schedule_job (job_id, job_group, job_triggers_group,\n" +
                "                                    job_trigger_name, job_cron, created, last_update_time)\n" +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";
        return insert(sql, scheduleJob.getJobId(), scheduleJob.getJobGroup(), scheduleJob.getJobTriggersGroup(),
                scheduleJob.getJobTriggerName(), scheduleJob.getJobCron(), scheduleJob.getCreated(),
                scheduleJob.getLastUpdateTime());
    }

    @Override
    public int updateCronOfScheduleJob(int scheduleJobId, String jobCron) throws SQLException {
        String sql = "update fast_cron_schedule_job set job_cron = ? where id = ?";
        return update(sql, jobCron, scheduleJobId);
    }

    @Override
    public int removeCronOfScheduleJob(int scheduleJobId) throws SQLException {
        String sql = "update fast_cron_schedule_job set `status` = ? where id = ?";
        return update(sql, -2, scheduleJobId);
    }

    @Override
    public List<Map<String, Object>> listScheduleJob() throws SQLException {
        String sql = "select id,fast_cron_schedule_job.job_id,fast_cron_job.job_name,\n" +
                "  fast_cron_job.job_detail, fast_cron_job.job_command,job_cron,\n" +
                "  fast_cron_schedule_job.created, fast_cron_schedule_job.last_update_time,\n" +
                "  fast_cron_schedule_job.`status` from fast_cron_schedule_job\n" +
                "left join fast_cron_job on fast_cron_schedule_job.job_id = fast_cron_job.job_id\n" +
                "order by fast_cron_schedule_job.created asc ;";
        return query(sql);
    }

}